var WxParse = require('../../wxParse/wxParse.js');
var util = require('../../utils/util.js');
var app = getApp();

Page({
  data: {
    topImages: [],
    isShow: false,
    imgurl: '',
    sliderOffset: 0,
    sliderLeft: 0,
    tabChecked: "special",
    yfPrice: 0, // 运费
    choiceType: '', // sh：加入购弹层；bu:立即购弹层；ap_pt：拼团全价；pp_pt：拼团;pp_ct：参团
    goodsId: 0,
    kfPhone: '',
    goods: '', // 产品
    ggList: '', // 产品规格集合
    ggListArr: '', // 筛选规格
    ggValue0: '',
    ggValue1: '',
    ggValue2: '', 
    vaArr: [],
    goodsGg: {}, // 选中规格
    chPrice: '',
    onePrice: '', // 单价
    chStock: '',
    goodNum: '1',
    imagewidth: 375,//缩放后的宽  
    imageheight: 375,//缩放后的高
    actionSheetHidden: true,
    // 拼团
    isTrueGroup: false, // 是否开团
    groupCount: 0,
    ptList5: [],
    morePtflag: true,// 更多
    cjPtflag: true, // 参团
    ptList10: [],
    ptTimeArr2: {},
    ptTimeArr5: {},
    groupItem: {},// 参团
    cjTimeclock: ''
  },
  onShareAppMessage: function (res) {
    var goodsId = this.data.goodsId
    var good = this.data.goods
    return {
      title: good.goodsName+good.goodsIntroduce,
      path: '/pages/goods/goodDetail?id=' + goodsId,
      success: function (res) {
        console.log('转发成功了')
      },
      fail: function (res) {
        console.log('转发失败了')
      }
    }
  },
  onLoad: function (options) {
    var that=this;
    //获取屏幕宽高  
    wx.getSystemInfo({
      success: function (res) { 
        var windowWidth = res.windowWidth;
        var windowHeight = res.windowHeight;
        that.setData({
          imagewidth: windowWidth,
          imageheight: windowWidth
        })
        console.log('宽:' + windowWidth + '高:' + windowWidth);
      }
    })
    // 页面初始化 options为页面跳转所带来的参数
    var that = this;
    that.setData({ imgurl: app.imageUrl })
    var id = options.id
    that.setData({ goodsId: id })
    wx.showLoading({
      title: '加载中',
    })
    that.getGoodById()
  },
  imageLoad: function (e) {
    var imageSize = util.imageUtil(e)
    this.setData({
      imagewidth: imageSize.imageWidth,
      imageheight: imageSize.imageHeight
    })
  }, 
  tabClick: function (e) {
    console.log(e.currentTarget.dataset.tip)
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id,
      tabChecked: e.currentTarget.dataset.tip
    });
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  onPullDownRefresh: function () {
    this.getGoodById()
  },
  bindToShopCar: function () {//购物车
    wx.switchTab({
      url: '../shopcar/shopcar'
    })
  },
  initConfig: function() {
    if(wx.getExtConfig) {
      wx.getExtConfig({
        success: function (res) {
          var shopId = res.extConfig.shopId;
          app.shopId = res.extConfig.shopId;
        }
      })
    }
  },
  getGoodById: function () {
    var that = this
    var header = { 'content-type': 'application/x-www-form-urlencoded' }
    var params = { goodsId: that.data.goodsId}
    var encodingStr = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/cx/retail/getGoodsInfo.htm',
      data: encodingStr,
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr)
        if (rest.isSuccess == 0) {
          var good = rest.goods
          console.log(good)
          var img = good.goodsImg
          var imgArr = []
          if (img != null && img != '') {
            imgArr = img.split('|')
          }
          var list = rest.ggList
          var ggListArr = that.optionsGgList(list)
          // 计算运费
          var yf = 0
          var extype = good.expressType
          if (extype == 'postage') {//统一邮费
            yf = good.postage
          } else {//运费模板
            yf = good.expressPirce
          }
          that.setData({
            goods: good, topImages: imgArr, chPrice: good.price, onePrice: good.price, chStock: good.stocks,
            ggList: list, ggListArr: ggListArr, yfPrice: yf
          })
          //产品详情绑定数据
          WxParse.wxParse('goodDetail', 'html', good.goodsDetail, that, 0);
        } else {
          wx.showModal({
            title: '提示',
            content: rest.errorMsg,
            showCancel: false,
            success: function () {
              wx.switchTab({
                url: '../index/index',
              })
            }
          })
        }
      },
      complete: function () {
        wx.stopPullDownRefresh()
        wx.hideLoading()
        that.setData({ isShow: true })
      }
    })
    
  },
  optionsGgList: function (list){//处理规格集合
    var that = this
    var result = [] // 返回嵌套集合
    var ggObj = {} // 规格object
    var ggArr1 = [], ggArr2 = [], ggArr3 = []
    var ggt1 = '', ggt2 = '', ggt3 = ''
    for(var i = 0; i < list.length; i++){
      if (ggt1 == ''){
        ggt1 = list[i].ggTypeOne
      }
      if (ggt2 == '') {
        ggt2 = list[i].ggTypeTwo
      }
      if (ggt3 == '') {
        ggt3 = list[i].ggTypeThree
      }
      if (ggt1 != null && ggt1 != ''){
        var gg1 = list[i].ggOne
        if(gg1 != null && gg1 != ''){
          let ish = that.contains(ggArr1, gg1)
          if(!ish){
            ggArr1.push(gg1)
          }
        }
      }
      if (ggt2 != null && ggt2 != '') {
        var gg2 = list[i].ggTwo
        if (gg2 != null && gg2 != '') {
          let ish = that.contains(ggArr2, gg2)
          if (!ish) {
            ggArr2.push(gg2)
          }
        }
      }
      if (ggt3 != null && ggt3 != '') {
        var gg3 = list[i].ggThree
        if (gg3 != null && gg3 != '') {
          let ish = that.contains(ggArr3, gg3)
          if (!ish) {
            ggArr3.push(gg3)
          }
        }
      }
    }
    if (ggArr1 != '') {
      var ob = { ggType: ggt1, ggName: ggArr1 }
      result.push(ob)
    }
    if (ggArr2 != '') {
      var ob = { ggType: ggt2, ggName: ggArr2 }
      result.push(ob)
    }
    if (ggArr3 != '') {
      var ob = { ggType: ggt3, ggName: ggArr3 }
      result.push(ob)
    }
    return result
  },
  contains: function (arr, obj) {
    var i = arr.length;  
    while(i--) {
      if (arr[i] === obj) {
        return true;
      }
    }  
    return false;  
  },
  // 客服
  actionSheetTap: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },
  actionSheetbindchange: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },
  bindOnline: function () {// 在线客服
    this.setData({ actionSheetHidden: !this.data.actionSheetHidden })
  },
  bindPhoneCall: function () { // 客服电话
    this.setData({ actionSheetHidden: !this.data.actionSheetHidden })
    var phone = this.data.kfPhone
    if (phone == null || phone == '') {
      wx.showModal({ title: '提示', content: '商家未提供电话！', showCancel: false })
      return
    }
    wx.makePhoneCall({
      phoneNumber: phone,
      success: function () {
        console.log('success_do')
      },
      fail: function () {
        console.log('fail_donot')
      }
    })
  },
  // 规格弹出层
  setModalStatus: function (e) {
    var that = this
    var tp = e.currentTarget.dataset.type
    that.setData({ choiceType: tp })
    // 一键拼团计算价格
    var price = 0
    if (tp == "pp_pt" || tp == "pp_ct") {
      price = e.currentTarget.dataset.ptprice
    } else {
      var ob = that.data.goodsGg
      if (JSON.stringify(ob) == "{}"){
        var good = that.data.goods
        price = good.price
      }else{
        price = ob.price
      }
    }
    that.setData({ onePrice: price, chPrice: price })

    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export()
    })
    if (e.currentTarget.dataset.status == 1) {
      this.setData({ showModalStatus: true })
    }
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (e.currentTarget.dataset.status == 0) {
        this.setData({ showModalStatus: false })
      }
    }.bind(this), 100)
  },
  bindGg:function(e){// 存在规格，选择时触发
    var value = e.currentTarget.dataset.opt
    var index = e.currentTarget.dataset.num
    if(index == 0){
      this.setData({ ggValue0: value, isChoice: true })
    } else if(index == 1){
      this.setData({ ggValue1: value, isChoice: true })
    } else if(index == 2){
      this.setData({ ggValue2: value, isChoice: true })
    }
    var arr = []
    var v0 = this.data.ggValue0, v1 = this.data.ggValue1, v2 = this.data.ggValue2
    var len = this.data.ggListArr.length// 规格数量
    arr.push(v0)
    arr.push(v1)
    arr.push(v2)
    this.setData({ vaArr:arr })
    if (len == 3){
      if (v0 != '' && v1 != '' && v2 != '') { this.checkGg(v0, v1, v2)}
    } else{
      this.checkGg(v0, v1, v2)
    }
  },
  checkGg: function (v0, v1, v2){// 获得选中规格
    var list = this.data.ggList
    var num = parseInt(this.data.goodNum)
    var ggOb = {}
    for (var i = 0; i < list.length; i++){
      if (list[i].ggOne == v0 && list[i].ggTwo == v1 && list[i].ggThree == v2){
        ggOb = list[i]
        var pri = (ggOb.price * num).toFixed(2)
        var ty = this.data.choiceType
        if (ty == 'pp_pt' || ty == 'pp_ct'){
          pri = (ggOb.groupPrice * num).toFixed(2)
        }
        this.setData({ goodsGg: ggOb, chPrice: pri, chStock: ggOb.stock })
        break
      }
    }
  },
  incNum:function(){
    var that = this
    var num = parseInt(that.data.goodNum)
    var ob = that.data.goodsGg
    if (JSON.stringify(ob) == "{}"){// 无规格
      var list = that.data.ggListArr
      if(list.length == 0){
        var pri = parseFloat(that.data.onePrice)
        that.setData({ goodNum: num + 1, chPrice: (pri*(num+1)).toFixed(2) })
      }
    }else{
      var pri = (parseFloat(ob.price) * (num + 1)).toFixed(2)
      var ty = that.data.choiceType
      if (ty == 'pp_pt' || ty == 'pp_ct'){
        pri = (parseFloat(ob.groupPrice) * (num + 1)).toFixed(2)
      }
      that.setData({ goodNum: num + 1, chPrice: pri })
    }
  },
  decNum: function () {
    var that = this
    var num = parseInt(that.data.goodNum)
    var ob = that.data.goodsGg
    if(num == 1){
      return
    }else{
      if (JSON.stringify(ob) == "{}") {// 无规格
        var list = that.data.ggListArr
        if (list.length == 0) {
          var pri = parseFloat(that.data.onePrice)
          that.setData({ goodNum: num - 1, chPrice: (pri * (num - 1)).toFixed(2) })
        }
      } else {
        var pri = (parseFloat(ob.price) * (num - 1)).toFixed(2)
        var ty = that.data.choiceType
        if (ty == 'pp_pt' || ty == 'pp_ct') {
          pri = (parseFloat(ob.groupPrice) * (num - 1)).toFixed(2)
        }
        that.setData({ goodNum: num - 1, chPrice: pri })
      }
    }
  },
  // 弹层方法--立即购买
  bindBuyGood: function (e) {
    
  },
  dateFormat: function(microSecond) {
    if (microSecond <= 0){
      return '00:00:00'
    }
    var second = Math.floor(microSecond / 1000) // 秒数
    
    var hr = Math.floor(second / 3600) // 小时位
    var min = this.fillZero(Math.floor((second - hr * 3600) / 60)) // 分钟位
    var sec = this.fillZero((second - hr * 3600 - min * 60)) // 秒位
    // var micro_sec = this.fillZero(Math.floor((microSecond % 1000) / 10)) // 毫秒位，保留2位
    
    return hr + ":" + min + ":" + sec
  },
  // 位数不足补零
  fillZero: function (num) {
    return num < 10 ? "0" + num : num
  },
})
